package com.camel.docker.utils;

import com.camel.docker.entity.Result;
import com.camel.docker.entity.search.ContainerAddForm;
import com.camel.docker.enums.ResultEnum;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 解释Docker返回的错误信息，尽量以能懂得的方式展现出来
 */
public class DockerClientExceptionUtils {
    private static final String CONTAINER_NAME_ALREADY_IN_USE = "(.+)The container name(.+)is already in use by container(.+)";
    private static final String IMAGE_ALREADY_IN_USE = "(.+)unable to delete(.+)image is being used by running container(.+)";



    public static Result trans(String msg, ContainerAddForm containerAddForm) {
        if(isMach(CONTAINER_NAME_ALREADY_IN_USE, msg)) {
            return ResultUtil.error(ResultEnum.NOT_VALID_PARAM, "容器名称 " + containerAddForm.getName() + " 已经被使用了");
        }
        if(isMach(IMAGE_ALREADY_IN_USE, msg)) {
            return ResultUtil.error(ResultEnum.NOT_VALID_PARAM, "该镜像正在被使用");
        }
        return ResultUtil.error(ResultEnum.NOT_VALID_PARAM, msg);
    }

    public static boolean isMach(String p, String msg) {
        return buildPattern(p).matcher(msg).matches();
    }

    public static Pattern buildPattern(String p) {
       return Pattern.compile(p);
    }
}
